package com.ghc.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.ghc.util.UuidUtil;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileUploadAction extends ActionSupport {
	private File file;      //接收这个上传的文件  
    private String fileFileName;     //Struts2提供的格式，在文件名后+FileName就是上传文件的名字 
	private String url;
	
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	@SuppressWarnings("static-access")
	@Override
	public String execute() throws Exception {
		String[] str = { ".jpg", ".jpeg", ".bmp", ".gif", ".png" };
		List<String> extList = Arrays.asList(str);
		// 限定文件大小是3MB
		if (file == null || file.length() > 3145728) {
			url = "imageError";
			return "error";
		}
		String fileExt = fileFileName.substring(fileFileName.lastIndexOf(".")).toLowerCase();
		if (extList.contains(fileExt)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
				UuidUtil uuidUtil = new UuidUtil();
				String FileName=fileFileName.substring(0, fileFileName.lastIndexOf("."));
				fileFileName = FileName.replace(FileName,sdf.format(new Date())+uuidUtil.generateShortUuid()+fileExt);
				//fileFileName = uuidUtil.generateShortUuid() + "-" + fileFileName;

				String path = ServletActionContext.getServletContext()
						.getRealPath("/upload");// 实际路径
				File saveFile = new File(new File(path), fileFileName); // 在该实际路径下实例化一个文件
				// 判断父目录是否存在
				if (!saveFile.getParentFile().exists()) {
					saveFile.getParentFile().mkdirs();
				}
				try {
					// 执行文件上传
					// FileUtils 类名 org.apache.commons.io.FileUtils;
					// 是commons-io包中的，commons-fileupload 必须依赖
					// commons-io包实现文件上传，实际上就是将一个文件转换成流文件进行读写
					FileUtils.copyFile(file, saveFile);
					url = "upload/" + fileFileName;
					return SUCCESS;
				} catch (IOException e) {
					url = "imageError";
					return "error";
				}
				} else {
			url = "imageError";
			return "error";
		}
		
	}
}
